'use client'

import { useEffect, useRef } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
import NProgress from 'nprogress'

// 配置 NProgress
NProgress.configure({
  minimum: 0.3,
  easing: 'ease',
  speed: 500,
  showSpinner: true
})

export default function NProgressProvider() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const isNavigating = useRef(false)

  useEffect(() => {
    // 页面加载时立即显示进度条
    NProgress.start()
    
    // 延迟一点时间确保页面内容已加载
    const timer = setTimeout(() => {
      NProgress.done()
    }, 100)

    return () => {
      clearTimeout(timer)
      NProgress.done()
    }
  }, [pathname, searchParams])

  useEffect(() => {
    // 监听页面刷新事件
    const handleBeforeUnload = () => {
      NProgress.start()
    }

    // 监听页面可见性变化（从其他标签页回来时）
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'visible') {
        NProgress.done()
      }
    }

    // 监听浏览器前进后退
    const handlePopState = () => {
      NProgress.start()
    }

    // 监听页面加载完成
    const handleLoad = () => {
      NProgress.done()
    }

    // 监听 DOM 内容加载完成
    const handleDOMContentLoaded = () => {
      NProgress.done()
    }

    // 添加事件监听器
    window.addEventListener('beforeunload', handleBeforeUnload)
    window.addEventListener('popstate', handlePopState)
    window.addEventListener('load', handleLoad)
    document.addEventListener('DOMContentLoaded', handleDOMContentLoaded)
    document.addEventListener('visibilitychange', handleVisibilityChange)

    // 页面初始加载时显示进度条
    if (document.readyState === 'loading') {
      NProgress.start()
    }

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload)
      window.removeEventListener('popstate', handlePopState)
      window.removeEventListener('load', handleLoad)
      document.removeEventListener('DOMContentLoaded', handleDOMContentLoaded)
      document.removeEventListener('visibilitychange', handleVisibilityChange)
      NProgress.done()
    }
  }, [])

  return null
} 